<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Illuminate\Http\Request;

class RoleController extends Controller {

	public function __construct() {
		$this->middleware('role:system');
	}

	/**
	 * 角色列表
	 */
	public function getIndex() {
		$listUrl = url('admin/role');
		session(['listUrl' => $listUrl]);
		$rows = Role::orderBy('id', 'ASC')->get();
		return view('admin/role/list', ['rows' => $rows]);
	}

	/**
	 * 访问角色用户列表页面
	 */
	public function getUserList($id = 0) {
		$users = Role::find($id)->users;
		$data = ['users' => $users, 'id' => $id];
		return view('admin/role/users', $data);
	}

	/**
	 * 进入角色成员列表页面
	 */
	public function getMemberList($id = 0) {
		$data = Role::find($id);
		return view('admin/role/members', $data);
	}

	/**
	 * 获取成员分页列表
	 */
	public function getMemberRows(Request $request) {
		$role_id = intval($request->input('role_id'));
		$kw = strval($request->input('kw'));
		$page = to_limit_lng($request->input('page'), 1);
		$limit = to_limit_lng($request->input('limit'), 1);
		$offset = ($page - 1) * $limit;

		$query = User::join('role_user', 'users.id', '=', 'role_user.user_id');
		$query->where('role_id', $role_id)->where(function ($q) use ($kw) {
			$q->where('username', 'LIKE', '%' . $kw . '%');
			$q->orWhere('realname', 'LIKE', '%' . $kw . '%');
			$q->orWhere('email', 'LIKE', '%' . $kw . '%');
			$q->orWhere('mobile', 'LIKE', '%' . $kw . '%');
		});
		$total_rows = $query->count();
		$rows = $query->orderBy('id', 'ASC')->skip($offset)->take($limit)->get();
		foreach ($rows as $row) {
			$row->avatar = get_avatar($row->id);
		}
		$data['rows'] = $rows;

		$data['total_rows'] = $total_rows;
		$data['page_count'] = ceil($total_rows / $limit);
		$data['page'] = $page;

		return $this->response($data);
	}

	/**
	 * 获取非当前角色的成员列表
	 */
	public function getOuterMemberRows(Request $request) {
		$role_id = intval($request->input('role_id'));
		$kw = strval($request->input('kw'));
		$page = to_limit_lng($request->input('page'), 1);
		$limit = to_limit_lng($request->input('limit'), 1);
		$offset = ($page - 1) * $limit;

		$query = User::leftJoin('role_user', 'users.id', '=', 'role_user.user_id');
		$query->where(function ($q) use ($kw) {
			$q->where('username', 'LIKE', '%' . $kw . '%');
			$q->orWhere('realname', 'LIKE', '%' . $kw . '%');
			$q->orWhere('email', 'LIKE', '%' . $kw . '%');
			$q->orWhere('mobile', 'LIKE', '%' . $kw . '%');
		});
		$query->distinct()->where(function ($q) use ($role_id) {
			$q->where('role_id', '<>', $role_id)->orWhereNull('role_id');
		});
		$total_rows = $query->count();
		$rows = $query->orderBy('id', 'ASC')->skip($offset)->take($limit)->get();
		foreach ($rows as $row) {
			$row->avatar = get_avatar($row->id);
		}
		$data['rows'] = $rows;
		$data['total_rows'] = $total_rows;
		$data['page_count'] = ceil($total_rows / $limit);
		$data['page'] = $page;

		return $this->response($data);
	}

	/**
	 * 获取成员信息
	 */
	public function getMemberInfo(Request $request) {
		$user_id = intval($request->input('user_id'));
		$user = User::find($user_id);
		if (empty($user)) {
			return $this->error('无效的成员');
		}
		$user->avatar = get_avatar($user->id);
		$data['user'] = $user;
		$data['profile'] = $user->profile;
		return $this->response($data);
	}

	/**
	 * 获取当前角色外的用户列表
	 */
	public function getUsersList(Request $request) {
		$id = intval($request->input('id'));
		$cur_users = Role::find($id)->users;
		$cur_user_ids = [];
		foreach ($cur_users as $user) {
			$cur_user_ids[] = $user->id;
		}
		$all_users = User::all();
		$users = [];
		foreach ($all_users as $user) {
			if (!in_array($user->id, $cur_user_ids)) {
				$user->profile;
				$user->avatar = get_avatar($user->id);
				$users[] = $user->toArray();
			}
		}
		return $this->response($users);
	}

	/**
	 * 获取权限列表
	 */
	public function getPermissionsList($id = 0) {
		$perms = Permission::all();

		$role = Role::find($id);
		$rows = $role->perms;
		$cur_perm_ids = [];
		foreach ($rows as $row) {
			$cur_perm_ids[] = $row->id;
		}

		$data = compact('id', 'role', 'perms', 'cur_perm_ids');
		return view('admin/role/qxs', $data);
	}

	/**
	 * 进入增加角色页面
	 */
	public function getAdd() {
		return view('admin/role/add');
	}

	/**
	 * 新增角色
	 */
	public function postInsert(Request $request) {
		$token = session('token');
		if ($token['isHidden'] == false) {
			return $this->warning('Access denied.');
		}

		$name = safe($request->input('name'), 50);
		$fullname = safe($request->input('fullname'));
		$description = safe($request->input('description'), 200);

		if (Role::where('name', $name)->count()) {
			return $this->warning('权限名称重复');
		}

		$role = new Role();
		$role->name = $name;
		$role->fullname = $fullname;
		$role->description = $description;
		$role->save();

		return redirect(session('listUrl'));
	}

	/**
	 * 获取单个角色信息
	 */
	public function getInfo(Request $request) {
		$id = $request->input('id');
		$role = Role::find($id);
		return $this->response($role);
	}

	/**
	 * 修改角色信息
	 */
	public function postUpdate(Request $request) {
		$id = intval($request->input('id'));
		$role = Role::find($id);
		if (empty($role)) {
			return $this->error('无效的角色');
		}
		if ($request->exists('fullname')) {
			$role->fullname = safe($request->input('fullname'));
		}
		if ($request->exists('description')) {
			$role->description = safe($request->input('description'), 200);
		}
		if ($role->save()) {
			return $this->response($role);
		} else {
			return $this->error('操作失败');
		}
	}

	/**
	 * 删除角色
	 */
	public function postDelete(Request $request) {
		$token = session('token');
		if ($token['isHidden'] == false) {
			return $this->error('Access denied.');
		}
		$id = intval($request->input('id'));
		$role = Role::findOrFail($id);
		$role->delete();
		$role->users()->sync([]);
		$role->perms()->sync([]);
		$role->forceDelete();
		return $this->response('ok');
	}

	/**
	 * 增加角色用户
	 */
	public function postUserAdd(Request $request) {
		$role_id = intval($request->input('id'));
		$user_id = intval($request->input('user_id'));
		$role = Role::find($role_id);
		$user = User::find($user_id);
		if ($user->hasRole($role->name) == false) {
			$user->roles()->attach($role_id);
		}
		return $this->response('ok');
	}

	/**
	 * 移除角色用户
	 */
	public function postRemoveUser(Request $request) {
		$role_id = intval($request->input('id'));
		$user_id = intval($request->input('user_id'));
		if ($user_id == 1 AND $role_id == 1) {
			return $this->error('系统管理员用户的角色被锁定');
		}
		$user = User::find($user_id);
		$user->roles()->detach($role_id);
		return $this->response('ok');
	}

	/**
	 * 增加角色权限
	 */
	public function postPermAdd(Request $request) {
		$role_id = intval($request->input('id'));
		$perm_id = intval($request->input('perm_id'));
		if ($role_id == 1 AND $perm_id == 1) {
		} else {
			$role = Role::find($role_id);
			$role->perms()->attach($perm_id);
		}
		return $this->response('ok');
	}

	/**
	 * 移除角色权限
	 */
	public function postRemovePerm(Request $request) {
		$role_id = intval($request->input('id'));
		$perm_id = intval($request->input('perm_id'));
		if ($role_id == 1 AND $perm_id == 1) {
			return $this->error('系统管理员的系统管理权限被锁定');
		} else {
			$role = Role::find($role_id);
			$role->perms()->detach($perm_id);
		}
		return $this->response('ok');
	}
}
